package com.gugee.ins.data.analysis.service.impl;

import com.gugee.common.thread.ScheduleTemplate;
import com.gugee.ins.common.constant.RedisKeyConst;
import com.gugee.ins.common.dal.service.blogger.InsBloggerDao;
import com.gugee.ins.common.dal.service.blogger.InsBloggerMainDao;
import com.gugee.ins.common.model.mysql.blogger.InsBlogger;
import com.gugee.ins.data.analysis.config.InsAnalysisConfig;
import com.gugee.ins.data.analysis.service.InsAnalysisAccountCheckUnusualService;
import com.gugee.ins.data.analysis.service.InsAnalysisAccountUnusualService;
import com.gugee.ins.data.common.msg.InsBloggerMessage;
import com.xiguaji.boot.toolkit.ThreadPoolUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.util.List;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.TimeUnit;

/**
 * InsAnalysisAccountUnusualImpl 服务
 * @author Huangxin
 */
@Slf4j
@Service
public class InsAnalysisAccountUnusualImpl implements InsAnalysisAccountUnusualService {

    /**
     * 配置
     */
    @Autowired
    InsAnalysisConfig insAnalysisConfig;

    /**
     * 线程调度
     */
    @Autowired
    ScheduleTemplate scheduleTemplate;

    /**
     * redis
     */
    @Autowired
    RedisTemplate<String,String> redisTemplate;

    /**
     * InsBloggerDao
     */
    @Autowired
    InsBloggerDao insBloggerDao;

    /**
     * InsBloggerDao
     */
    @Autowired
    InsBloggerMainDao insBloggerMainDao;

    /**
     * 线程池
     */
    ForkJoinPool forkJoinPool;

    /**
     *
     */
    @Autowired
    InsAnalysisAccountCheckUnusualService insAnalysisAccountCheckUnusualService;

    /**
     * 线程名
     */
    private String workName = "insAnalysisAccountUnusual-worker";

    /**
     * 初始化线程池
     */
    @PostConstruct
    public void init() {
        forkJoinPool = ThreadPoolUtils.forkJoinPool(insAnalysisConfig.getInsAnalysisAccountUnusualCorePollSize(), workName);
        scheduleTemplate.attach(workName, forkJoinPool);
    }

    /**
     * 处理调用uid接口body 为 null 的情况
     * @param insBloggerMessages
     */
    @Override
    public void handleAnalysisAccountUnusual(List<InsBloggerMessage> insBloggerMessages) {
        try {
            forkJoinPool.submit(() -> insBloggerMessages.parallelStream().forEach(msg -> {
                try {
                    analysisAccountUnusual(msg);
                } catch (Exception ex) {
                    log.error("insAnalysisAccountUnusual error. uid:{}, error :{}" ,
                            msg.getUid(),ex.getMessage());
                }
            })).get();
        } catch (Exception ex) {
            log.error("insAnalysisAccountUnusual thread error.  {}" ,  ex.getMessage());
        }
    }

    /**
     * 处理调用uid接口body 为 null 的情况
     * @param insBloggerMessage
     */
    public void analysisAccountUnusual(InsBloggerMessage insBloggerMessage){
        long start = System.currentTimeMillis();
        long uid = insBloggerMessage.getUid();
        // redis key
        String key = RedisKeyConst.INS_SPIDER_UNUSUAL + uid;
        // 判断 redis 里是否有该uid
        Boolean isNotExist = redisTemplate.opsForValue().setIfAbsent(key,1 + "",insAnalysisConfig.getInsAnalysisAccountCheckUnusualRedisTimeoutDay(), TimeUnit.DAYS);
        if(isNotExist != null && isNotExist){
            // 不存在，查询一次库，判断是否已经销号
            InsBlogger insBlogger = insBloggerDao.findByUid(uid);
            if(insBlogger != null){
                if(insBlogger.getAccountStatus() == 1){
                    // 已经是销号的了 删除redis
                    redisTemplate.delete(key);
                }
                // 获取粉丝数量判断是否是大博主，判断添加redis队列方向
                if(insBlogger.getAccountStatus() == 0){
                    boolean isMb = insBlogger.getFollowerCount() >= insAnalysisConfig.getInsBloggerMainFollowerCountMin();
                    if(isMb){
                        redisTemplate.opsForList().leftPush(RedisKeyConst.INS_SPIDER_UNUSUAL_LIST,uid + "");
                    }else{
                        redisTemplate.opsForList().rightPush(RedisKeyConst.INS_SPIDER_UNUSUAL_LIST,uid + "");
                    }
                }
            }
        } else {
            // 存在该uid ，自增1
            insAnalysisAccountCheckUnusualService.checkUnusual(key,uid);
        }

        if ((System.currentTimeMillis() - start) / 1000 > insAnalysisConfig.getInsAnalysisDebugTimeLimit()) {
            log.info("insAnalysisAccountUnusual uid:{} use time:{}s", uid,(System.currentTimeMillis() - start) / 1000);
        }
    }
}
